from shutil import copyfile
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import os

def open_file():
    global file_path
    file_path = filedialog.askopenfilename(title="选择固件文件")
    i = 0
    if not file_path:
        messagebox.showerror("错误", "未选择文件。")
        return
    if not file_path.endswith('.bin'):
        messagebox.showerror("错误", "请选择一个.bin格式的固件文件。")
        return
    copyfile(file_path, "./fw_mac_tmp.bin")
    with open("./fw_mac_tmp.bin", 'rb+') as file:
        file.seek(0x1fc000)
        mac_bytes = [file.read(1).hex() for _ in range(6)]
    current_mac = ":".join(mac_bytes)
    label_mac_current.config(text=f"{current_mac}")

def write_mac():
    new_mac = mac_input_box.get()
    if not new_mac:
        messagebox.showerror("错误", "未输入新的MAC地址。")
        return
    if len(new_mac) != 17:
        messagebox.showerror("错误", "无效的MAC地址格式。")
        return
    new_mac_bytes = bytes(int(x, 16) for x in new_mac.split(':'))
    if not os.path.exists("./fw_mac_tmp.bin"):
        messagebox.showerror("错误", "未选择文件, 请先打开固件文件。")
        return
    with open("./fw_mac_tmp.bin", 'rb+') as file:
        file.seek(0x1fc000)
        file.write(new_mac_bytes)
    messagebox.showinfo("信息", "MAC地址更新完成，并保存为新文件。")
    copyfile("./fw_mac_tmp.bin", f'./fw_mac_{new_mac_bytes.hex()}.bin')

window = tk.Tk()
window.title("JerryTech网件MAC地址修改工具")
window.geometry("400x300")
label_mac_init = tk.Label(window)
label_mac_init.config(text="当前固件MAC地址：")
label_mac_init.place(x=30, y=50)
label_mac_current = tk.Label(window)
label_mac_current.place(x=30, y=80)
label_mac_new = tk.Label(window)
label_mac_new.config(text="新固件MAC地址,用英文冒号分隔开：")
label_mac_new.place(x=30, y=110)
mac_input_box = tk.Entry(window)
mac_input_box.place(x=30, y=140)

file_btn = tk.Button(window, text="打开固件文件", command=open_file)
file_btn.place(x=50, y=200)
write_btn = tk.Button(window, text="写入MAC地址", command=write_mac)
write_btn.place(x=250, y=200)

window.mainloop()

if os.path.exists("./fw_mac_tmp.bin"):
	os.remove("./fw_mac_tmp.bin")
	
